<?php

/**
 * Executes the youtube search and shows the result.
 * 
 * @param String $input
 */
function ajax_search($input)
{
	parse_str($input, $formData);
	
	$html = file_get_contents("https://www.youtube.com/results?search_query=" . urlencode($formData['searchString']));
	preg_match_all('/href="\/watch\?v=(...........)"/Uis', $html, $matches);
	$matches = array_keys(array_flip($matches[1]));
	$html = '';
	foreach ($matches as $id) {
		$html .= "<li class='ui-state-default'><input type='hidden' name='playlistIds[]' value='$id' /><a href='https://www.youtube.com/watch?v=$id' target='_blank'><img class='dragAndDropImage' src='//i.ytimg.com/vi/$id/mqdefault.jpg' /></a></li>";
	}
	$html .= "<input type='hidden' name='playlistIds[]' value='playlistStart' />";
	Ajax::addResponse()->document->getElementById('sortable1')->innerHTML = $html;
}

/**
 * Saves the playlist.
 *
 * @param String $input        	
 */
function ajax_playlistSave($input)
{
	$query = 'DELETE FROM playlist WHERE server_id="' . Application::$mysqli->escape_string($_REQUEST['tp']) . '" AND client_id="' . Application::$mysqli->escape_string(Application::$_browserId) . '"';
	Application::$mysqli->query($query);
	
	parse_str($input, $formData);
	$playlistIds = array();
	$saveIds = false;
	$sortsequence = 0;
	foreach ($formData['playlistIds'] as $playlistId) {
		if ($saveIds) {
			$query = 'INSERT INTO playlist (`server_id`, `client_id`, `sortsequence`, `video_id`) VALUES ( 
                "' . Application::$mysqli->escape_string($_REQUEST['tp']) . '", 
                "' . Application::$mysqli->escape_string(Application::$_browserId) . '", 
                ' . $sortsequence ++ . ', 
                "' . Application::$mysqli->escape_string($playlistId) . '")';
			Application::$mysqli->query($query);
		} else {
			if ($playlistId == 'playlistStart')
				$saveIds = true;
		}
	}
	Ajax::addResponse()->alert("Playlist saved!");
}

/**
 * Shows the actual playlist for the server.
 *
 * @param integer $input        	
 */
function ajax_getPlaylistHtml($input)
{
	$html = '';
	$playlist = array();
	$videosCount = 0;
	$query = 'SELECT * FROM playlist WHERE server_id="' . Application::$mysqli->escape_string(Application::$_browserId) . '" ORDER BY client_id ASC, sortsequence ASC';
	if ($result = Application::$mysqli->query($query)) {
		while ($row = $result->fetch_assoc()) {
			$playlist[$row['client_id']][$row['sortsequence']] = $row['video_id'];
			$videosCount ++;
		}
		$result->free();
	}
	
	$playlistMerged = array();
	$playlistKeys = array_keys($playlist);
	for ($i = $input; $i < $input + 12; $i ++) {
		$client_id = $playlistKeys[$i % count($playlistKeys)];
		$playlistMerged[] = $playlist[$client_id][floor($i / count($playlistKeys)) % count($playlist[$client_id])];
	}
	
	$firstVideo = true;
	foreach ($playlistMerged as $video_id) {
		if ($firstVideo) {
			$html .= '<input type="hidden" id="firstVideo" value="' . htmlspecialchars($video_id) . '" />';
			$firstVideo = false;
		}
		$html .= '<img src="//i.ytimg.com/vi/' . $video_id . '/mqdefault.jpg" />';
	}
	
	Ajax::addResponse()->document->getElementById('playlistServer')->innerHTML = $html;
	Ajax::addResponse()->document->getElementById('info')->innerHTML = 'Clients: ' . count($playlistKeys) . ' | Videos: ' . $videosCount;
}
